﻿using AutoMapper;
using B.S.Medical.Api.Write.Application.Command.Department;
using B.S.Medical.Api.Write.Common;
using B.S.Medical.Domain.Department;
using B.S.Medical.ErrorCode;
using B.S.Medical.Infrastructure.Interface;
using MediatR;

namespace B.S.Medical.Api.Write.Application.Handler.Department
{
    public class AddDepartmentCommandHandle : IRequestHandler<AddDepartmentCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<ManageModel> _manageRepository;
        private readonly IBaseRepository<LogModel> _logRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<AddDepartmentCommandHandle> _logger;
        private readonly IIdentityService _identityService;

        public AddDepartmentCommandHandle(
            IBaseRepository<ManageModel> manageRepository, 
            IBaseRepository<LogModel> logRepository,
            IMapper mapper, 
            ILogger<AddDepartmentCommandHandle> logger,
            IIdentityService identityService)
        {
            _manageRepository = manageRepository;
            _logRepository = logRepository;
            _mapper = mapper;
            _logger = logger;
            _identityService = identityService;
        }

        public async Task<ApiResult<int>> Handle(AddDepartmentCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var manage=_mapper.Map<ManageModel>(request);
            manage.IsDeleted = false;
            var r = await _manageRepository.CreateAsync(manage);
            if(r>0)
            {
                res.Msg="新增科室成功!";
                res.Code=ApiEnum.Success;
                _logger.LogInformation($"新增科室{manage.DepartmentName}成功");
                res.Data = r;
                
                // 记录日志到数据库
                await RecordLogToDatabase(manage.DepartmentName, r);
            }
            else
            {
                res.Msg = "新增科室失败!";
                res.Code = ApiEnum.Fail;
                _logger.LogError($"新增科室{manage.DepartmentName}失败");
                res.Data = r;
            }
            return await Task.FromResult(res);
        }
        
        /// <summary>
        /// 记录日志到数据库
        /// </summary>
        /// <param name="departmentName">科室名称</param>
        /// <param name="departmentId">科室ID</param>
        private async Task RecordLogToDatabase(string departmentName, int departmentId)
        {
            try
            {
                var currentTime = DateTime.Now;
                
                // 记录调试信息
                _logger.LogInformation($"身份服务调试信息：");
                _logger.LogInformation($"是否已认证：{_identityService.IsAuthenticated}");
                _logger.LogInformation($"用户ID：{_identityService.UserId}");
                _logger.LogInformation($"用户名：{_identityService.UserName}");
                _logger.LogInformation($"真实姓名：{_identityService.RealName}");
                _logger.LogInformation($"显示名称：{_identityService.DisplayName}");
                _logger.LogInformation($"所有声明：{_identityService.GetAllClaims()}");
                
                var currentUser = _identityService.DisplayName;
                
                // 如果无法获取用户信息，使用默认值
                if (string.IsNullOrEmpty(currentUser))
                {
                    currentUser = "未知用户";
                    _logger.LogWarning("无法获取当前登录用户信息，使用默认值");
                }
                
                var logModel = new LogModel
                {
                    CreateTime = currentTime,
                    UpdateTime = currentTime,
                    Creator = currentUser,
                    Updator = currentUser,
                    LogContent = $"{currentUser}添加了科室：{departmentName}（ID：{departmentId}）",
                    IsDeleted = false
                };
                
                await _logRepository.CreateAsync(logModel);
                _logger.LogInformation($"成功记录科室添加日志，用户：{currentUser}，科室：{departmentName}");
            }
            catch (Exception ex)
            {
                _logger.LogError($"记录科室添加日志失败：{ex.Message}");
            }
        }
        
    }
}
